package org.chaiyi.template.core.common.exception;

import lombok.Getter;

@Getter
public class BusinessError extends RuntimeException {
    private final String code;
    private final String msg;

    /**
     * {@link BusinessErrorType}
     */
    private String level;

    public BusinessError level(String level) {
        this.level = level;
        return this;
    }

    public BusinessError(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public void trigger() {
        trigger(BusinessErrorType.NORMAL);
    }

    public void trigger(String level) {
        this.level = level;
        throw this;
    }

    public void throwIf(boolean condition) {
        throwIf(condition, BusinessErrorType.NORMAL);
    }

    public void throwIf(boolean condition, String level) {
        if (condition) {
            this.level = level;
            throw this;
        }
    }

    public String toJson() {
        String jsonFmt = """
                {"code":"%s","msg":"%s","level":"%s"}
                """;
        return String.format(jsonFmt, code, msg, level);
    }
}
